package com.luohh.treeroom.util;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

import java.lang.reflect.Field;
import java.util.*;

public class StringUtil {

    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNotEmpty(CharSequence cs) {
        return !isEmpty(cs);
    }

    public static boolean isBlank(String str) {
        if (null == str || 0 == str.length() || "".equals(str.trim()) || "null".equals(str)
                || "null".equals(str.trim())) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isNotBlank(String str) {
        if (null == str || 0 == str.length() || "".equals(str.trim()) || "null".equals(str)
                || "null".equals(str.trim())) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 转换成string类型
     * 
     * @param obj
     * @return
     */
    public static String transStringValue(Object obj) {
        return "null".equals(String.valueOf(obj)) ? "" : String.valueOf(obj);
    }

    public static String replaceOnce(String text, String searchString, String replacement) {
        return replace(text, searchString, replacement, 1);
    }

    /**
     * 
     * @param text
     * @param searchString
     * @param replacement
     * @param max
     * @return
     */
    public static String replace(String text, String searchString, String replacement, int max) {
        if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0)
            return text;
        int start = 0;
        int end = text.indexOf(searchString, start);
        if (end == -1)
            return text;
        int replLength = searchString.length();
        int increase = replacement.length() - replLength;
        increase = increase >= 0 ? increase : 0;
        increase *= max >= 0 ? max <= 64 ? max : 64 : 16;
        StringBuilder buf = new StringBuilder(text.length() + increase);
        do {
            if (end == -1)
                break;
            buf.append(text.substring(start, end)).append(replacement);
            start = end + replLength;
            if (--max == 0)
                break;
            end = text.indexOf(searchString, start);
        } while (true);
        buf.append(text.substring(start));
        return buf.toString();
    }

    /**
     * 把Map中的KEY转换成小写
     * 
     * @param mapData
     * @return
     */
    public static Map<String, Object> keyLowerCaseTrans(Map<String, Object> mapData) {
        Map<String, Object> result = new HashMap();

        for (Map.Entry<String, Object> entry : mapData.entrySet()) {
            result.put(entry.getKey().toString().toLowerCase(), entry.getValue());
        }
        return result;
    }

    /**
     * 对象转map
     * 
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }

        return map;
    }

    /**
     * json转Map，注意导入的json的jar包是net.sf.json，不是alibaba的fastjson
     */
    public static Map<String, Object> parseJSON2Map(String jsonStr) {
        if (jsonStr == "" || jsonStr == null) {
            return null;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            // 最外层解析
            JSONObject json = JSONObject.fromObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                // 如果内层还是数组的话，继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<Object> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = (JSONObject) it.next();
                        list.add(parseJSON2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        }
    }

    /**
     * xml格式转Map
     */
    public static Map<String, Object> xmlToMap(String xmlStr) {
        if (xmlStr == "" || xmlStr == null) {
            return null;
        } else {
            XMLSerializer xmlSerializer = new XMLSerializer();
            JSON json = (JSON) xmlSerializer.read(xmlStr);

            return parseJSON2Map(json.toString());
        }
    }

    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是浮点数
     */
    public static boolean isDouble(String value) {
        try {
            Double.parseDouble(value);
            if (value.contains("."))
                return true;
            return false;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是数字
     */
    public static boolean isNumber(String value) {
        return isInteger(value) || isDouble(value);
    }

    /**
     * 随机字符串
     */
    public static String getRandomString(int length) { // length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
